//
//  AddRecordTableViewController.m
//  ProjectB
//
//  Created by lanou on 16/5/11.
//  Copyright © 2016年 lanou. All rights reserved.
//

#import "AddRecordTableViewController.h"
#import "Record.h"
#import "NSString+StringColor.h"
#import "YYCoreDataHandlerRecord.h"
#import <SVProgressHUD.h>
#import "ChooseTableViewController.h"
#import "EditViewController.h"
#import "AppDelegate.h"

@interface AddRecordTableViewController ()

@property (nonatomic, strong) NSArray *colorArray;
@property (nonatomic, strong) NSArray *colorNameArray;

@property (nonatomic, strong) UISwitch *topSwitch;
@property (nonatomic, strong) UISwitch *remindSwitch;
@property (nonatomic, strong) UIView *colorView;
@property (nonatomic, assign) BOOL isAdd;
@property (nonatomic, strong) UIView *backgroundView;
@property (nonatomic, strong) UIView *pickerView;
@property (nonatomic, strong) UIDatePicker *datePicker;

@end

@implementation AddRecordTableViewController

- (NSString *)category {
    if (!_category) {
        _category = [self.allCategories firstObject];
    }
    return _category;
}

- (NSString *)colorName {
    if (!_colorName) {
        _colorName = [self.colorNameArray objectAtIndex:3];
    }
    return _colorName;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    self.title = @"添加事件";
    self.tableView.scrollEnabled = NO;
    
    _colorArray = [[NSArray alloc] initWithObjects:[UIColor whiteColor], [UIColor colorWithRed:1.000 green:0.000 blue:0.000 alpha:0.555], [UIColor colorWithRed:0.000 green:1.000 blue:0.000 alpha:0.508], [UIColor colorWithRed:0.000 green:0.000 blue:1.000 alpha:0.564], [UIColor colorWithRed:0.000 green:1.000 blue:1.000 alpha:0.519], [UIColor colorWithRed:1.000 green:1.000 blue:0.000 alpha:0.546], [UIColor colorWithRed:1.000 green:0.000 blue:1.000 alpha:0.536], [UIColor colorWithRed:1.000 green:0.500 blue:0.000 alpha:0.567], [UIColor colorWithRed:0.500 green:0.000 blue:0.500 alpha:0.533], [UIColor colorWithRed:0.600 green:0.400 blue:0.200 alpha:0.594], [UIColor lightGrayColor], nil];
    _colorNameArray = [[NSArray alloc] initWithObjects:@"白色", @"红色", @"绿色", @"蓝色", @"青蓝色", @"黄色", @"品红色", @"橙色", @"紫色", @"棕色", @"灰色", nil];
    
    if (self.record) {
        self.navigationController.navigationBar.items.lastObject.backBarButtonItem = [UIBarButtonItem createBackItem];
        _isAdd = NO;
    } else {
        UIBarButtonItem *cancelItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(cancel)];
        self.navigationItem.leftBarButtonItem = cancelItem;
        _isAdd = YES;
    }
    
    UIBarButtonItem *confirmItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStyleDone target:self action:@selector(confirm)];
    self.navigationItem.rightBarButtonItem = confirmItem;
    
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
}

- (void)cancel {
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

- (void)confirm {
    if ([self.recordTitle isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"请输入标题"];
        return;
    }
    
    if (self.date == nil) {
        [SVProgressHUD showErrorWithStatus:@"请输入日期"];
        return;
    }
    
    if (!_record) {
        _record = [YYCoreDataHandlerRecord getNewManagedObject];
    }
    
    NSString *title = self.record.title;
    
    self.record.title = self.recordTitle;
    self.record.category = self.category;
    self.record.backgroundColor = self.colorName;
    self.record.createDate = [NSDate dateWithTimeIntervalSinceNow:60 * 60 * 8];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:self.date];
    components.calendar = [NSCalendar currentCalendar];
    components.timeZone = [NSTimeZone systemTimeZone];
    components.hour = 8;
    components.minute = 0;
    components.second = 0;
    self.record.recordDate = components.date;
    self.record.top = @(self.topSwitch.on);
    self.record.remind = @(self.remindSwitch.on);
    self.record.other = self.other;
    
    if (self.remindSwitch.on) {
        BOOL isAdd = YES;
        for (UILocalNotification *ln in [UIApplication sharedApplication].scheduledLocalNotifications) {
            if ([[ln.userInfo objectForKey:@"record"] isEqualToString:title]) {
                [[UIApplication sharedApplication] cancelLocalNotification:ln];
                ln.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:self.recordTitle, @"record", self.category, @"category", nil];
                ln.fireDate = self.date;
                if ([self.category isEqualToString:@"纪念日"]) {
                    ln.repeatInterval = NSCalendarUnitYear;
                } else {
                    ln.repeatInterval = 0;
                }
                [[UIApplication sharedApplication] scheduleLocalNotification:ln];
                isAdd = NO;
                break;
            }
        }
        
        if (isAdd) {
            UILocalNotification *myLocalNotification = [[UILocalNotification alloc] init];
            myLocalNotification.fireDate = self.record.recordDate;
            myLocalNotification.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:self.recordTitle, @"record", self.category, @"category", nil];
            myLocalNotification.timeZone = [NSTimeZone systemTimeZone];
            myLocalNotification.alertBody = self.recordTitle;
            myLocalNotification.soundName = UILocalNotificationDefaultSoundName;
            myLocalNotification.repeatCalendar = [NSCalendar currentCalendar];
            if ([self.record.category isEqualToString:@"纪念日"]) {
                myLocalNotification.repeatInterval = NSCalendarUnitYear;
            }
            
            [[UIApplication sharedApplication] scheduleLocalNotification:myLocalNotification];
        }
        
    } else {
        for (UILocalNotification *ln in [UIApplication sharedApplication].scheduledLocalNotifications) {
            if ([[ln.userInfo objectForKey:@"record"] isEqualToString:title]) {
                [[UIApplication sharedApplication] cancelLocalNotification:ln];
            }
        }
    }
    
    if (self.isAdd) {
        if (![[YYCoreDataHandlerRecord sharedCoreDataHandler] insertObject:self.record]) {
            [SVProgressHUD showErrorWithStatus:@"该标题已经存在"];
            return;
        }
//        self.completeBlock(self.record);
        [self cancel];
    } else {
        [[YYCoreDataHandlerRecord sharedCoreDataHandler] saveContext];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 7;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // Configure the cell...
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
    switch (indexPath.row) {
        case 0:
            cell.textLabel.text = @"标题";
            cell.detailTextLabel.text = self.recordTitle;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            break;
        case 1:
            cell.textLabel.text = @"分类";
            cell.detailTextLabel.text = self.category;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            break;
        case 2:
            cell.textLabel.text = @"背景颜色";
            if (!self.colorView) {
                _colorView = [[UIView alloc] initWithFrame:CGRectMake(kScreenWidth - 75, 5, 40, 30)];
            }
            _colorView.backgroundColor = [self.colorName stringColor];
            [cell.contentView addSubview:_colorView];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            break;
        case 3:
        {
            cell.textLabel.text = @"日期";
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setCalendar:[NSCalendar currentCalendar]];
            [dateFormatter setDateFormat:@"YYYY-MM-dd"];
            if (self.date) {
                cell.detailTextLabel.text = [dateFormatter stringFromDate:self.date];
            }
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            break;
        }
//        case 4:
//            cell.textLabel.text = @"置顶";
//            if (!_topSwitch) {
//                _topSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(kScreenWidth - 60, 0, 60, 40)];
//                _topSwitch.on = self.isTop;
//                [cell.contentView addSubview:_topSwitch];
//            }
//            break;
        case 4:
            cell.textLabel.text = @"提醒";
            if (!_remindSwitch) {
                _remindSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(kScreenWidth - 60, 5, 60, 30)];
                _remindSwitch.on = self.isRemind;
                [cell.contentView addSubview:_remindSwitch];
                break;
            }
        case 5:
            cell.textLabel.text = @"备注";
            cell.detailTextLabel.text = self.other;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            break;
            
        default:
            break;
    }
    
    return cell;
}

- (void)createDatePicker {
    AppDelegate *delegate = [UIApplication sharedApplication].delegate;
    if (!self.backgroundView) {
        _backgroundView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        _backgroundView.backgroundColor = [UIColor blackColor];
        [delegate.window addSubview:_backgroundView];
        self.backgroundView.alpha = 0.5;
        self.backgroundView.hidden = YES;
    }
    
    if (!self.pickerView) {
        _pickerView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight, kScreenWidth, 250)];
        _pickerView.backgroundColor = [UIColor whiteColor];
        [delegate.window addSubview:_pickerView];
        
        UIButton *cancel = [UIButton buttonWithType:UIButtonTypeSystem];
        cancel.frame = CGRectMake(0, 0, 40, 30);
        [cancel setTitle:@"取消" forState:UIControlStateNormal];
        cancel.tintColor = [UIColor blackColor];
        [cancel addTarget:self action:@selector(cancelPicker) forControlEvents:UIControlEventTouchUpInside];
        [_pickerView addSubview:cancel];
        
        UIButton *confirm = [UIButton buttonWithType:UIButtonTypeSystem];
        confirm.frame = CGRectMake(kScreenWidth - 40, 0, 40, 30);
        [confirm setTitle:@"完成" forState:UIControlStateNormal];
        confirm.tintColor = [UIColor blackColor];
        [confirm addTarget:self action:@selector(confirmPicker) forControlEvents:UIControlEventTouchUpInside];
        [_pickerView addSubview:confirm];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(40, 0, kScreenWidth - 80, 30)];
        label.textAlignment = NSTextAlignmentCenter;
        label.text = @"选择日期";
        [_pickerView addSubview:label];
        
        if (!self.datePicker) {
            _datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 30, kScreenWidth, 220)];
            _datePicker.datePickerMode = UIDatePickerModeDate;
            if (self.date) {
                _datePicker.date = self.date;
            }
            [_pickerView addSubview:_datePicker];
        }
    }
    
    [self showDatePicker];
}

- (void)showDatePicker {
    self.backgroundView.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        self.pickerView.transform = CGAffineTransformMakeTranslation(0, -250);
    }];
}

- (void)confirmPicker {
    self.date = self.datePicker.date;
    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:3 inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
    
    [self cancelPicker];
}

- (void)cancelPicker {
    self.backgroundView.hidden = YES;
    [UIView animateWithDuration:0.3 animations:^{
        self.pickerView.transform = CGAffineTransformMakeTranslation(0, 0);
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    switch (indexPath.row) {
        case 0:
        {
            EditViewController *editVC = [[EditViewController alloc] init];
            editVC.title = @"标题";
            editVC.text = self.recordTitle;
            editVC.block = ^(NSString *title) {
                self.recordTitle = title;
                [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            };
            [self.navigationController pushViewController:editVC animated:YES];
            break;
        }
        case 1:
        {
            ChooseTableViewController *chooseTVC = [[ChooseTableViewController alloc] initWithStyle:UITableViewStylePlain];
            chooseTVC.title = @"分类";
            chooseTVC.dataSource = self.allCategories;
            chooseTVC.block = ^(NSString *category) {
                self.category = category;
                [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            };
            [self.navigationController pushViewController:chooseTVC animated:YES];
            break;
        }
        case 2:
        {
            ChooseTableViewController *chooseTVC = [[ChooseTableViewController alloc] initWithStyle:UITableViewStylePlain];
            chooseTVC.title = @"背景颜色";
            chooseTVC.dataSource = self.colorNameArray;
            chooseTVC.block = ^(NSString *colorName) {
                self.colorName = colorName;
                [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            };
            [self.navigationController pushViewController:chooseTVC animated:YES];
            break;
        }
        case 3:
        {
            [self createDatePicker];
            break;
        }
        case 5:
        {
            EditViewController *editVC = [[EditViewController alloc] init];
            editVC.title = @"备注";
            editVC.text = self.other;
            editVC.block = ^(NSString *other) {
                self.other = other;
                [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            };
            [self.navigationController pushViewController:editVC animated:YES];
            break;
        }
            
        default:
            break;
    }
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Table view delegate

// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here, for example:
    // Create the next view controller.
    <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:<#@"Nib name"#> bundle:nil];
    
    // Pass the selected object to the new view controller.
    
    // Push the view controller.
    [self.navigationController pushViewController:detailViewController animated:YES];
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
